package ui;

import Figures.Figure;
import Tools.EventHandler;
import Tools.FiguresContainer;
import Tools.StatusManager;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 类功能描述：画板类继承自JPanel,用于显示图形
 * <br>通过画板中的鼠标事件来创建或改变图形的属性
 *
 * @author lix
 * @date 2023/12/28
 */

public class MyPanel extends JPanel {

    public MyPanel() {
        //1.绑定鼠标事件
        add_mouse_listen();
    }

    private Graphics2D g2d;

    public void setFiguresContainer(FiguresContainer figuresContainer) {
        this.figuresContainer = figuresContainer;
    }

    private FiguresContainer figuresContainer;//引入图形容器

    private StatusManager statusManager;//引入状态管理器
    public void setStatusManager(StatusManager statusManager) {
        this.statusManager = statusManager;
    }
    private EventHandler eventHandler;//引入事件处理器
    public void setEventHandler(EventHandler eventHandler) {
        this.eventHandler = eventHandler;
    }


    /**
     * 功能描述：利用Graphics对象在画板中进行绘制
     *
     * @param g Graphics对象
     * @author lix
     * @date 2023/12/29
     */

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g2d = (Graphics2D) g;
        //绘制容器里的图形
        drawContainer(figuresContainer,g2d);
    }

    //绑定鼠标事件
    public void add_mouse_listen() {
        MouseAdapter mouseAdapter = new MouseAdapter() {
            //鼠标点击事件
            @Override
            public void mouseClicked(MouseEvent e) {
                eventHandler.panel_clicked(statusManager,e);
            }
            //鼠标按压事件
            @Override
            public void mousePressed(MouseEvent e) {
                eventHandler.panel_pressed(statusManager,e);
            }

            //鼠标松开事件
            @Override
            public void mouseReleased(MouseEvent e) {
                eventHandler.panel_released(statusManager,e);
            }

            //鼠标移动事件
            @Override
            public void mouseMoved(MouseEvent e) {
                eventHandler.panel_moved(statusManager,e);
            }

            //鼠标拽动事件
            @Override
            public void mouseDragged(MouseEvent e) {
                eventHandler.panel_dragged(statusManager,e);
            }
        };

        this.addMouseListener(mouseAdapter);
        this.addMouseMotionListener(mouseAdapter);

    }

    /**
     * 功能描述：
     *遍历容器中的对象，调用对象的draw方法展示在画板上
     * @param container 图形容器
     * @param g2d Graphics2D对象
     * @author lix
     * @date 2023/12/29
     */

    private void drawContainer(FiguresContainer container,Graphics2D g2d){
        if(!container.isEmpty()){
            for(Figure figure : container.getFigures()){
                figure.Draw(g2d);
            }
        }
        if(container.getTemp_figure()!= null){
            container.getTemp_figure().Draw(g2d);
        }

    }

}
